package de.dhbw.karlsruhe.picsim.model.commands.impl;

import de.dhbw.karlsruhe.picsim.model.actions.ActionFactory;
import de.dhbw.karlsruhe.picsim.model.actions.PicAction;
import de.dhbw.karlsruhe.picsim.model.commands.PicInstruction;
import de.dhbw.karlsruhe.picsim.model.cpu.PicInstructionFacade;
import de.dhbw.karlsruhe.picsim.model.memory.impl.RegisterValueImpl;
import de.dhbw.karlsruhe.picsim.util.Bits;
import de.dhbw.karlsruhe.picsim.util.impl.BitUtilities;
import de.dhbw.karlsruhe.picsim.util.impl.Lengths;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: May 3, 2010
 * Time: 2:39:10 PM
 */
public final class AddLW implements PicInstruction {
    private static final Log log = LogFactory.getLog(AddLW.class);
    private final Bits argument;

    public AddLW(final Bits argument) {
        this.argument = BitUtilities.clone(argument);
        if (argument.getLength() != Lengths.FILE_LENGTH) {
            throw new IllegalArgumentException(argument.toString());
        }
    }

    @NotNull
    @Override
    public List<? extends PicAction> getActions(@NotNull final PicInstructionFacade pic) {
        log.debug("literal will be added to W");
        final int wFile = pic.getWRegister().getData().asInteger();
        final int literal = BitUtilities.fromLeastSignificantBitFirst(argument);

        final List<PicAction> list = new ArrayList<PicAction>();
        final ActionFactory actionFactory = pic.getActionFactory();
        final int result = AddWF.addDigtCarrygedoenst(list, actionFactory, wFile, literal);
        if (result == 0) {
            list.add(actionFactory.setZeroBit());
        } else {
            list.add(actionFactory.clearZeroBit());
        }
        list.add(actionFactory.createWriteInWAction(RegisterValueImpl.createUnsafe(result)));
        return list;
    }

}
